package org.mc.wsdemo.java;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.sql.*;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import org.mc.wsdemo.java.JDBCUtils;

@ServerEndpoint("/myWs")
@Component
@Slf4j
public class WsServerEndPoint {

    static Map<String,Session> sessionMap=new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session.getId(),session);
        log.info("websocket is open");
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session.getId());
        log.info("websocket is close");
    }

    @OnMessage
    public String onMessage(String Text) {
        // Handle incoming client messages if necessary
        log.info("收到了一条消息"+Text);
        return "已收到你的消息";
    }


    @Scheduled(fixedRate = 5000)
    public void sendMsg() throws IOException {
        JDBCUtils db=new JDBCUtils();
        String s=db.getdata();
        for(String key:sessionMap.keySet()){
            sessionMap.get(key).getBasicRemote().sendText(s);
        }
    }


}
